<#include "../../common/htmlwrap.ftl">

<@html>

    <@header title="${pageName}">

    <!--头像裁剪-->
    <link rel="stylesheet" href="${common.staticPath}plugins/baiduWebupload/dist/webuploader.css">
    <!--上传插件-->
    <!--https://fengyuanchen.github.io/cropper/-->
    <link rel="stylesheet" href="${common.staticPath}plugins/cropper/cropper.css">

    </@header>

<body>

<!-- Content Header (Page header) -->
    <@content_header title='${pageName}'></@content_header>

<section class="content">

    <div class="row">
        <!-- form start -->
        <form role="form" action="${form_url}" id="myform" class="form-horizontal">

            <input type="hidden" name="member_id" value="${member.id}">
            <div class="col-sm-12">
                <div class="box box-primary">
                <#--<div class="box-header with-border">
                    <h3 class="box-title">Quick Example</h3>
                </div>-->
                    <!-- /.box-header -->
                    <div class="box-body">

                        <div class="form-group">
                            <label for="input_name" class="col-sm-3 control-label">登录名</label>
                            <div class="col-sm-9">
                                <span style="display: block;padding: 6px 18px;">
                                ${member.loginname}
                                </span>
                            </div>
                        </div>

                        <!--昵称-->
                        <div class="form-group">
                            <label for="input_name" class="col-sm-3 control-label">昵称</label>
                            <div class="col-sm-9">
                                <input name="name" value="${member.name!""}"
                                       class="form-control" id="input_name"
                                       placeholder=""
                                       type="text"
                                       valType=""
                                       required>
                            </div>
                        </div>

                        <!--头像-->
                        <div class="form-group">
                            <label for="input_avatar" class="col-sm-3 control-label">头像</label>
                            <div class="col-sm-9">
                                <#assign avatar_default=common.staticPath+"img/avatar-select.jpg">

                                <#if member.avatar?? && member.avatar!="">

                                    <input type="hidden" name="avatar" id="input_avatar"
                                           value="${member.avatar}">
                                    <img src="${common.avatarPath+member.avatar}" class="img-responsive" id="img_avatar" alt="Image"
                                         style="float: left;height: 160px;width: 160px;">

                                <#else>

                                    <input type="hidden" name="avatar" id="input_avatar"
                                           value="">
                                    <img src="${avatar_default}" class="img-responsive" id="img_avatar" alt="Image"
                                         style="float: left;height: 160px;width: 160px;">

                                </#if>

                                <span class="btn btn-bitbucket open-avatar"><i
                                        class="fa fa-pencil-square"></i>上传图片</span>

                            </div>
                        </div>

                        <!--出生日期-->
                        <div class="form-group">
                            <label for="input_birthDate" class="col-sm-3 control-label">出生日期</label>
                            <div class="col-sm-9">
                                <input name="birthDate" value="${(member.birthDate?date)!""}"
                                       id="input_birthDate"
                                       class="form-control"
                                       type="text"
                                       valType="date"
                                       onclick="laydate({elem: '#input_birthDate'})"
                                >
                            </div>
                        </div>

                        <!--简介-->
                        <div class="form-group">
                            <label for="input_descript" class="col-sm-3 control-label">简介</label>
                            <div class="col-sm-9">
                                    <textarea id="input_descript"
                                              name="descript"
                                              class="form-control"
                                    >${member.descript!""}</textarea>
                            </div>
                        </div>


                        <!--性别-->
                        <div class="form-group">
                            <label class="col-sm-3 control-label">性别</label>
                            <div class="checkbox-list col-sm-9">
                                <#list sexEnum as val>
                                    <label class="checkbox-inline">
                                        <input type="radio" name="sex" value="${val.getValue()}"
                                            <#if val.getValue()==(member.sex.getValue())!'UNKNOW'>
                                               checked
                                            </#if>
                                        >${val.getTitle()}</label>
                                </#list>
                            </div>
                        </div>

                    </div>

                    <!-- /.box-body -->

                    <div class="box-footer">
                        <button type="button" onclick="close_iframe()" class="btn btn-default">关闭</button>
                        <button type="submit" class="btn btn-info pull-right">保存</button>
                    </div>
                </div>
            </div>
        </form>
    </div>

</section>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">
                    <span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <!--<h4 class="modal-title" id="myModalLabel"></h4>-->
            </div>
            <div class="modal-body">
                <div class="row" id="avatar-container" style="padding-top: 10px">
                    <div class="col-md-6">
                        <div class="image-crop">
                            <img src="${avatar_default}"
                                 id="avatarimg" class="img-responsive"
                                 alt="Image">
                        </div>
                    </div>
                    <div class="col-md-6">
                        <h4>图片预览：</h4>
                        <div class="img-preview"
                             style="overflow:hidden;width:160px;height: 160px;"></div>
                        <div class="btn-group" id="cropper-btns" data-toggle="buttons">
                            <button class="btn btn-adn" id="zoomIn" type="button">放大</button>
                            <button class="btn btn-adn" id="zoomOut" type="button">缩小</button>
                            <button class="btn btn-github" id="rotateLeft" type="button">左旋转</button>
                            <button class="btn btn-github" id="rotateRight" type="button">右旋转</button>
                        <#--<button class="btn btn-warning" id="setDrag" type="button">裁剪</button>-->
                        </div>
                        <div class="clearfix"></div>
                        <div class="btn-group">
                            <div id="avatar-picker">选择头像</div>
                        <#--<input type="button" id="avatar-picker" class="form-control" value="选择头像">-->
                            <input type="button" id="avatar-upload" class="form-control" value="上传">
                        </div>
                    </div>
                </div>
            </div>
        <#--<div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        &lt;#&ndash;<button type="button" class="btn btn-primary">Save changes</button>&ndash;&gt;
        </div>-->
        </div>
    </div>
</div>

    <@footer_edit>


    <script src="${common.staticPath}plugins/baiduWebupload/dist/webuploader.min.js"></script>
    <script src="${common.staticPath}plugins/cropper/cropper.js"></script>
    <!--bootstrap 弹窗-->
    <!--<script src="${common.staticPath}plugins/bootbox/bootbox.js"></script>-->
    <!--头像裁剪和上传-->
    <script type="text/javascript">
        var avatar_url = "${avatar_url}";
        var avatar_default = "${avatar_default}";
        (function (factory) {
            if (!window.jQuery) {
                alert('jQuery is required.')
            }

            jQuery(function () {
//                var $container = $("#avatar-container");

                factory.call(null, jQuery);

            });
        })(function ($) {
// -----------------------------------------------------
// ------------ START ----------------------------------
// -----------------------------------------------------

// ---------------------------------
// ---------  Uploader -------------
// ---------------------------------
            var Uploader = (function () {

                // -------setting-------
                // 如果使用原始大小，超大的图片可能会出现 Croper UI 卡顿，所以这里建议先缩小后再crop.
                var FRAME_WIDTH = 1600;

                var _ = WebUploader;
                var Uploader = _.Uploader;
                var uploader, file;

                if (!Uploader.support()) {
                    alert('Web Uploader 不支持您的浏览器！');
                    throw new Error('WebUploader does not support the browser you are using.');
                }

                // hook,
                // 在文件开始上传前进行裁剪。
                Uploader.register({
                    'before-send-file': 'cropImage'
                }, {

                    cropImage: function (file) {

                        //上传文件之前的时候会执行这个函数

                        var data = file._cropData,
                                image, deferred;

                        file = this.request('get-file', file);
                        deferred = _.Deferred();

                        image = new _.Lib.Image();

                        deferred.always(function () {
                            image.destroy();
                            image = null;
                        });

                        //注册回调函数
                        image.once('error', deferred.reject);
                        image.once('load', function () {
                            //调用loadFromBlob后的回调
                            image.crop(data.x, data.y, data.width, data.height, data.scale);
                        });

                        image.once('complete', function () {
                            var blob, size;

                            // 移动端 UC / qq 浏览器的无图模式下
                            // ctx.getImageData 处理大图的时候会报 Exception
                            // INDEX_SIZE_ERR: DOM Exception 1
                            try {
                                blob = image.getAsBlob();
                                size = file.size;
                                file.source = blob;
                                file.size = blob.size;

                                file.trigger('resize', blob.size, size);

                                deferred.resolve();
                            } catch (e) {
                                console.log(e);
                                // 出错了直接继续，让其上传原始图片
                                deferred.resolve();
                            }
                        });

                        file._info && image.info(file._info);
                        file._meta && image.meta(file._meta);

                        //开始读取文件blob进行xxx
                        image.loadFromBlob(file.source);
                        return deferred.promise();
                    }
                });

                var curFile = null;

                var _onMakeThumb;
                var _onUploadProgress;
                var _onUploadComplete;
                var _onUploadSuccess;

                return {
                    init: function () {

                        var _this = this;

                        uploader = new Uploader({
                            pick: {
                                id: '#avatar-picker',
                                multiple: false
                            },

                            // 设置用什么方式去生成缩略图。
                            thumb: {
                                quality: 70,

                                // 不允许放大
                                allowMagnify: false,

                                // 是否采用裁剪模式。如果采用这样可以避免空白内容。
                                crop: false
                            },

                            // 禁掉分块传输，默认是开起的。
                            chunked: false,

                            // 禁掉上传前压缩功能，因为会手动裁剪。
                            compress: false,

                            // fileSingleSizeLimit: 2 * 1024 * 1024,

                            server: avatar_url,
                            swf: '../../dist/Uploader.swf',
                            fileNumLimit: 1,
                            onError: function () {
                                var args = [].slice.call(arguments, 0);
                                alert(args.join('\n'));
                            }
                        });

                        uploader.on("uploadError", function (file, reason) {
                            layer.msg("上传过程中出现了一些问题:" + reason, {icon: 2, time: 5000});
                        });

                        //当文件被加入队列之前触发
                        uploader.on("beforeFileQueued", function (file) {

                            //选择一个新文件,把原来的文件移除出队列
                            if (curFile != null) {
                                uploader.removeFile(curFile, true);
                            }
                            curFile = file;

                        });

                        // 文件上传过程中创建进度条实时显示。
                        uploader.on('uploadProgress', function (file, percentage) {
                            _onUploadProgress && _onUploadProgress(percentage);
                        });

                        uploader.on("uploadSuccess", function (file, response) {
                            _onUploadSuccess && _onUploadSuccess(file, response);
                        });

                        uploader.on("uploadComplete", function (file) {
                            _onUploadComplete && _onUploadComplete(file);
                            uploader.reset();
                            uploader.removeFile(file);
                            curFile = null;
//                            uploader.addFile(curFile);
//                            curFile = file = null;
                        });

                        //当选择了新文件
                        uploader.on('fileQueued', function (_file) {
                            file = _file;

                            uploader.makeThumb(file, function (error, src) {

                                if (error) {
                                    alert('不能预览');
                                    return;
                                }

                                _onMakeThumb && _onMakeThumb(src);

                            }, FRAME_WIDTH, 1);   // 注意这里的 height 值是 1，被当成了 100% 使用。

                        });
                    },

                    crop: function (data) {

                        //一开始的图像百度给压缩预览了,所以要计算scale
                        var scale = Croper.getImageSize().width / file._info.width;
                        data.scale = scale;

                        file._cropData = {
                            x: data.x,
                            y: data.y,
                            width: data.width,
                            height: data.height,
                            scale: data.scale
                        };
                        console.log("file._cropData", file._cropData);
                    },

                    upload: function () {
                        curFile && uploader.upload(curFile);
//                        uploader.reset();
                    },
                    isSelectFile: function () {
                        return curFile != null;
                    },
                    onMakeThumb: function (callback) {
                        _onMakeThumb = callback;
                    },
                    onUploadProgress: function (callback) {
                        _onUploadProgress = callback;
                    },
                    onUploadComplete: function (callback) {
                        _onUploadComplete = callback;
                    },
                    onuploadSuccess: function (callback) {
                        _onUploadSuccess = callback;
                    }
                };
            })();

// ---------------------------------
// ---------  Crpper ---------------
// ---------------------------------
            var Croper = (function () {
                var $image = $("#avatarimg");//显示的图片
                var $btns = $("#cropper-btns");//一些操作按钮

                var isBase64Supported;

                function srcWrap(src, cb) {

                    // we need to check this at the first time.
                    if (typeof isBase64Supported === 'undefined') {
                        (function () {
                            var data = new Image();
                            var support = true;
                            data.onload = data.onerror = function () {
                                if (this.width != 1 || this.height != 1) {
                                    support = false;
                                }
                            };
                            data.src = src;
                            isBase64Supported = support;
                        })();
                    }

                    if (isBase64Supported) {
                        cb(src);
                    } else {
                        // otherwise we need server support.
                        // convert base64 to a file.
                        $.ajax('../../server/preview.php', {
                            method: 'POST',
                            data: src,
                            dataType: 'json'
                        }).done(function (response) {
                            if (response.result) {
                                cb(response.result);
                            } else {
                                alert("预览出错");
                            }
                        });
                    }
                }

                $btns.on('click', 'button', function () {
                    var $button = $(this);
                    var id = $button.attr("id");
                    if (id == "zoomIn") {
                        $image.cropper("zoom", 0.15);
                    } else if (id == "zoomOut") {
                        $image.cropper("zoom", -0.15);
                    } else if (id == "rotateLeft") {
                        $image.cropper("rotate", -90);
                    } else if (id == "rotateRight") {
                        $image.cropper("rotate", 90);
                    }

                });

                return {
                    init: function () {

                        var cropperOptions = {
                            aspectRatio: 16 / 16,
                            preview: ".img-preview",
                            done: function (data) {
                                // console.log(data);
                            }
                        };
                        $image.cropper(cropperOptions);

                    },
                    setSource: function (src) {

                        // 处理 base64 不支持的情况。
                        // 一般出现在 ie6-ie8
                        srcWrap(src, function (src) {
//                            $image.cropper("setImgSrc", src);
//                            var uploadedImageURL = URL.createObjectURL(file);
                            $image.cropper('replace', src);
                        });

                        return this;
                    },

                    getImageSize: function () {
                        var img = $image.get(0);
                        return {
                            width: img.naturalWidth,
                            height: img.naturalHeight
                        }
                    },

                    getData: function () {
                        return $image.cropper("getData");
                    },

                    disable: function () {
                        $image.cropper("disable");
                        return this;
                    },

                    enable: function () {
                        $image.cropper("enable");
                        return this;
                    },

                    setImgSrc:function (src) {
                        $image.cropper('replace', src);
                    }
                };

            })();

            /*var a = function bb() {
                return {str:"bb"};
            };
            var c = new a();*/

            var Progresser = (function () {

                function Progress() {
                    this.layer_index = null;
                    this.$percent = null;
                }

                Progress.prototype = {
                    init: function () {
                        var _this = this;
                        this.layer_index = layer.open({
                            type: 1,
                            title: false,
                            area: '500px;',
                            closeBtn: 0,
                            shadeClose: true,
                            skin: 'yourclass',
                            content: '<div class="progress progress-striped active" style=""><div class="progress-bar" role="progressbar" style="width: 100%;"></div></div>',
                            success: function (layero) {
                                _this.$percent = layero.find('.progress .progress-bar');
                            }
                        });
                        return this.layer_index;//当作id
                    },
                    setProgress: function (percentage) {
                        this.$percent.css('width', percentage * 100 + '%');
                    },
                    destory: function () {
                        layer.close(this.layer_index);
                    }
                };

                var progress;

                return {
                    create: function () {
                        progress = new Progress();
                        progress.init();
                    },
                    setProgress: function (percentage) {
                        progress.setProgress(percentage);
                    },
                    destory: function () {
                        progress.destory();
                    }
                };
            })();


// ------------------------------
// -----------logic--------------
// ------------------------------
            var btn = $('#avatar-upload');//上传按钮

            var markedThumb = false;

            Uploader.onMakeThumb(function (src) {
                Croper.setSource(src);
                markedThumb = true;
            });
            Uploader.onUploadProgress(function (percentage) {
                console.log("percentage", percentage);
                Progresser.setProgress(percentage);
            });
            Uploader.onUploadComplete(function () {
                markedThumb = false;
                Progresser.destory();

                $modal.modal("hide");

                Croper.setImgSrc(avatar_default);
            });
            Uploader.onuploadSuccess(function (file, response) {
                if (response.success) {
                    var map=response.obj;
                    $("#img_avatar").attr("src", map.url);
                    $("#input_avatar").val(map.filename);
                } else {
                    layer.msg(response.msg, {icon: 2});
                }
            });

            btn.on('click', function () {
                if (markedThumb) {
                    var data = Croper.getData();
                    Uploader.crop(data);
                    Uploader.upload();
                    Progresser.create();
                } else {
                    layer.msg("请选择图片", {
                        icon: 2,
                        time: 3000 //（如果不配置，默认是3秒）
                    });
                }
                return false;
            });

            var $modal = $("#myModal");
            var started = false;
            $modal.on('shown.bs.modal', function (e) {
                if (!started) {
                    Croper.init();
                    Uploader.init();//创建
                    started = true;
                }
            });

            $("span.open-avatar").click(function () {
                //展开上传头像
                $modal.modal("show");
            });
// -----------------------------------------------------
// ------------ END ------------------------------------
// -----------------------------------------------------
        });
    </script>

    <!--表单-->
    <script>
        $(document).ready(function () {
            //表单
            var $form = $("#myform");

            $form.validatorX();

            $form.submit(function (event) {//$("button[type=submit]")
                event.preventDefault();
                //验证表单
                if (!$form.Valid()) {
                    return;
                }
                //发送ajax请求
                $.ajax({
                    url: $form.attr("action"),
                    type: "POST",
                    datatype: "json",
                    //timeout: 3000,
                    data: $form.serialize()
                }).done(function (data, textStatus) {
                    layerMsg(data.msg, data.success, function () {
                        if (data.success) {
                            close_iframe_or_refresh();
                        }
                    });
                }).fail(function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log("ajax error", XMLHttpRequest, textStatus, errorThrown);
                });
            });
        });

    </script>

    </@footer_edit>
</body>

</@html>